/**
 * Created by Mark_ren on 2016/11/28.
 * 苟富贵,無相忘
 */
var express = require('express');
var moment = require("moment");
var router = express.Router();
var co = require('co');
var seqModule = require('./createModules');
var seq = new seqModule();
var fs = require('fs');
var http = require('http');
var request = require('request');

var formidable = require('formidable');
var getIP = require('./getIP');


//查询用户信息/分页
router.get('/getDepartmentPage', function(req, res, next) {
    co(function () {
        var page=parseInt(req.query.page);
        var params={};
        var paramT={};
        if(req.query.id != undefined){
            params["id"]=parseInt(req.query.id);
        }
        //模糊查询
        if(req.query.name != undefined){
            params["name"]={"$like":"%"+req.query.name+"%"};

        }
        if(req.query.parentId != undefined){
            params["parentId"]=parseInt(req.query.parentId);

        }
        if(req.query.order != undefined){
            params["order"]=parseInt(req.query.order);

        }
        if(req.query.synTime != undefined){
            params["synTime"]=req.query.synTime;
        }

        paramT["where"]=params;
        paramT["order"]=[["order","DESC"]];
        if(req.query.page != undefined && req.query.rows !=undefined){
            paramT["offset"]=parseInt(req.query.page);
            paramT["limit"]=parseInt(req.query.rows);
        }
        seq.departmentModule.findAndCountAll(paramT).then(function(result){
            res.json({"success":true,"page":page,"total":result.count,"result":result.rows});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'查询失败'});
        console.log(e);
    })
});




router.get('/addDepartmernt', function(req, res, next) {
    co(function () {
        var jsonData = JSON.stringify({});
        request({
                url: "http://test.yunicu.com/tp_ccdt/nodeJs.action?getDepartment",
                method: "get",
                json: true,
                headers: {
                    "content-type": "application/json",
                },
                body: JSON.stringify(jsonData)
            },
            function(error, response, data) {
                if (!error && response.statusCode == 200) {
                    var JsonArr = data.result.department;
                    if(JsonArr.length > 0){
                        var nowTime = moment().format("YYYY-MM-DD HH:mm:ss");
                        var departSql = "insert into department values ";
                        var idArr = [];
                        for(var i=0;i<JsonArr.length;i++){
                            var val = JsonArr[i];
                            departSql+=" ("+val.id+",'"+val.name+"',"+val.parentid+","+val.order+",'"+nowTime+"'),"
                            idArr.push(val.id);
                        }
                        departSql=departSql.substring(0,departSql.lastIndexOf(","));
                        seq.departmentModule.destroy({'where':{'id':idArr}}).then(function(results){
                            seq.sequelize.query(departSql).spread(function(result){
                                res.json({'success':true,'msg':'添加成功','result':result});
                            })
                        });

                    }else{
                        res.json({'success':false,'msg':'暂无数据返回'});
                    }
                }else{
                    res.json({'success':false,'msg':'请求失败'});
                }
            });


    }).catch(function(e) {
        res.json({'success':false,'msg':'添加失败'});
        console.log(e);
    })
});

router.get('/addDepartEmployee', function(req, res, next) {
    co(function () {
        var departId = req.query.departId;
        var jsonData = JSON.stringify({});
        request({
                url: "http://test.yunicu.com/tp_ccdt/nodeJs.action?getDepartEmployee&departId="+departId,
                method: "get",
                json: true,
                headers: {
                    "content-type": "application/json",
                },
                body: JSON.stringify(jsonData)
            },
            function(error, response, data) {

                if (!error && response.statusCode == 200) {
                        var JsonArr = data.result.userlist;
                    if(JsonArr.length > 0){
                        var nowTime = moment().format("YYYY-MM-DD HH:mm:ss");
                        var departSql = "insert into memeber_respresent values ";
                        for(var i=0;i<JsonArr.length;i++){
                            var val = JsonArr[i];
                            var extattr = val.extattr;
                            if(extattr != null){
                                var attrs = extattr.attrs;
                            }
                            if(val.weixinid == undefined){
                                val.weixinid="";
                            }
                            if(val.avata == undefined){
                                val.avata="";
                            }
                            departSql+=" ('"+val.userid+"','"+attrs[0].value+"','"+val.avatar+"','"+val.name+"','"+val.mobile+"','"+val.email+"',"+val.gender+",'','','','"+val.position+"','','','','"+val.weixinid+"','','"+nowTime+"','"+val.department[0]+"','','','',''),"
                        }
                        departSql=departSql.substring(0,departSql.lastIndexOf(","));
                            seq.sequelize.query(departSql).spread(function(result){
                                res.json({'success':true,'msg':'添加成功','result':result});
                            })


                    }else{
                        res.json({'success':false,'msg':'暂无数据返回'});
                    }
                }else{
                    res.json({'success':false,'msg':'请求失败'});
                }
            });

    }).catch(function(e) {
        res.json({'success':false,'msg':'添加失败'});
        console.log(e);
    })
});

// //删除
router.get('/deleteDepartment', function(req, res, next) {
    co(function () {
        var params=req.query.params;
        var arr=params.split(",");
        var paramT=[arr];
        seq.departmentModule.destroy({'where':{'id':paramT}}).then(function(results){
            res.json({"success":true,"msg":"删除成功","rows":results});
        });
    }).catch(function(e) {
        res.json({'success':false,'msg':'删除失败'});
        console.log(e);
    })
});


module.exports = router;